package jjn.round1;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author Jjn
 * @since 2022-08-13 11:04
 */

public class LeetCode429_NArrayTreeLevelOrderTraversal {
    
    public List<List<Integer>> levelOrder(Node root) {
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        Queue<Node> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            List<Integer> currentLevel = new ArrayList<>();
            List<Node> next = new ArrayList<>();
            while (!queue.isEmpty()) {
                Node node = queue.poll();
                currentLevel.add(node.val);
                List<Node> children = node.children;
                if (children != null && children.size() > 0) {
                    next.addAll(children);
                }
            }
            result.add(currentLevel);
            for (Node node : next) {
                queue.offer(node);
            }
        }
        return result;
    }
}
